//
//  HYProtocolAlerView.m
//  XPlayer
//
//  Created by 张水 on 2023/11/16.
//

#import "HYProtocolAlerView.h"
#import <CommUtls.h>

#define leftMargin (50 *KAdapterScale)

typedef void(^CancelActionBlock)(void);
typedef void(^PrivacyAgreementBlock)(void);
typedef void(^UserAgreementBlock)(void);


@interface HYProtocolAlerView ()<UITextViewDelegate>
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UILabel *titleLable;
@property (nonatomic, strong) UIButton *agreeBtn;
@property (nonatomic, strong) UIButton *diagreeBtn;
@property (copy, nonatomic) CancelActionBlock cancelActionBlock;
@property (copy, nonatomic) PrivacyAgreementBlock privacyAgreementBlock;
@property (copy, nonatomic) UserAgreementBlock userAgreementBlock;
@end

@implementation HYProtocolAlerView

- (instancetype)init
{
    if (self = [super init]) {
        self.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.8];
        self.alpha = 0;
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [self addSubview:self.contentView];
        [self.contentView addSubview:self.titleLable];
        [self.contentView addSubview:self.textView];
        [self.contentView addSubview:self.agreeBtn];
        [self.contentView addSubview:self.diagreeBtn];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat width = kScreenWidth - leftMargin * 2;
    CGFloat margin = 20 * KAdapterScale;
    CGFloat titleLabelHeight = 20 * KAdapterScale;
    CGFloat textViewWidth = width - margin * 2;
    CGFloat btnHeight = margin * 2;
    CGFloat textViewHeight = [_textView.attributedText boundingRectWithSize:CGSizeMake(textViewWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height + margin;
    CGFloat contentViewHeight = titleLabelHeight + textViewHeight + btnHeight * 2 + margin * 2 + margin;
    CGFloat contentViewY = (kScreenHeight - contentViewHeight) / 2;
    self.contentView.frame = CGRectMake(leftMargin, contentViewY, kScreenWidth - leftMargin * 2, contentViewHeight);
    self.titleLable.frame = CGRectMake(margin, margin * 0.7, textViewWidth, titleLabelHeight);
    self.textView.frame = CGRectMake(margin, CGRectGetMaxY(self.titleLable.frame) + margin * 0.7, width - margin * 2, textViewHeight);
    self.agreeBtn.frame =
    CGRectMake(margin, CGRectGetMaxY(self.textView.frame) + margin *0.7, width - margin * 2, margin * 2);
    self.diagreeBtn.frame = CGRectMake(margin, CGRectGetMaxY(self.agreeBtn.frame), width - margin * 2, margin * 2);
}

- (void)showAlert:(UIViewController *)vc cancelAction:(void (^)(void))cancelAction  privateAction:(void (^)(void))privacyAction userAction:(void (^)(void))userAction
{
    [vc.view addSubview:self];
    [UIView animateWithDuration:1 animations:^{
        self.alpha = 1.0;
    }];
    self.cancelActionBlock = ^{
        !cancelAction ? :cancelAction();
    };
    self.privacyAgreementBlock = ^{
        !privacyAction ? : privacyAction();
    };
    self.userAgreementBlock = ^{
        !userAction ? : userAction();
    };
}

- (void)dismissAlertView:(UIButton *)btn
{
    if (btn.tag == 1) {
            [UIView animateWithDuration:1 animations:^{
                self.alpha = 0;
            } completion:^(BOOL finished) {
                [self removeFromSuperview];
            }];
        [HYMineSetManager shareManager].isAccepAgreement = YES;
    }else{
        !self.cancelActionBlock ? : self.cancelActionBlock();
    }
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction{
    /// 隐私
    if ([[URL scheme] isEqualToString:@"PrivacyAgreement"]){
        /// 跳转隐私政策界面
        !self.privacyAgreementBlock ? : self.privacyAgreementBlock();
        return NO;
    }
    /// 协议
    else if ([[URL scheme] isEqualToString:@"UserAgreement"]) {
        /// 跳转用户协议界面
        !self.userAgreementBlock ? : self.userAgreementBlock();
        return NO;
    }
    return YES;
}


- (void)setContent:(NSString *)content{
    _content = content;
    NSString *agreeStr = [NSString stringWithFormat:@"%@", content];/// @"我已阅读并同意《隐私政策》《用户协议》";
    NSMutableAttributedString *diffString = [[NSMutableAttributedString alloc] initWithString:agreeStr];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 5 * KAdapterScale;

    [diffString addAttribute:NSForegroundColorAttributeName value:APPTextThemeColor range:[[diffString string] rangeOfString:content]];
    
    [diffString addAttribute:NSLinkAttributeName
                       value:@"UserAgreement://"
                       range:[[diffString string] rangeOfString:[NSString stringWithFormat:NSLocalizedString(@"《用户协议》",nil)]]];/// 《用户协议》
    [diffString addAttribute:NSLinkAttributeName
                           value:@"PrivacyAgreement://"
                           range:[[diffString string] rangeOfString:[NSString stringWithFormat:NSLocalizedString(@"《隐私政策》",nil)]]];/// 《隐私政策》
   
    [diffString addAttributes:@{NSParagraphStyleAttributeName:paragraphStyle,
                                NSFontAttributeName:kIsIPad?FONT_SIZE(16):FONT_SIZE(14)
                                      } range:NSMakeRange(0, content.length)];
    self.textView.linkTextAttributes = @{NSForegroundColorAttributeName: [CommUtls colorWithHexString:@"#F8B62D"]};
    self.textView.attributedText = diffString;
}

- (UITextView *)textView
{
    if (_textView == nil) {
        _textView = [[UITextView alloc] init];
        _textView.scrollEnabled = NO;
        _textView.delegate = self;
        _textView.showsHorizontalScrollIndicator = NO;
        _textView.showsVerticalScrollIndicator = NO;
        _textView.textColor = APPTextThemeColor;
        _textView.font = kIsIPad?FONT_SIZE(16):FONT_SIZE(14);
        _textView.textContainer.lineFragmentPadding = 0;
        _textView.textContainerInset = UIEdgeInsetsZero;
        _textView.textAlignment = NSTextAlignmentLeft;
        _textView.editable = NO;
    }
    return _textView;
}

- (UIView *)contentView
{
    if (_contentView == nil) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = AppContentBgThemeColor;
        _contentView.layer.cornerRadius = 10 * KAdapterScale;
    }
    return _contentView;
}
- (UILabel *)titleLable
{
    if (_titleLable == nil) {
        _titleLable = [[UILabel alloc] init];
        _titleLable.textColor = APPTextThemeColor;
        _titleLable.font =  [UIFont systemFontOfSize:17];
        _titleLable.textAlignment = NSTextAlignmentCenter;
        _titleLable.text = NSLocalizedString(@"协议与隐私政策",nil);
    }
    return _titleLable;
}

- (UIButton *)agreeBtn
{
    if (_agreeBtn == nil) {
        _agreeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _agreeBtn.tag = 1 ;
        _agreeBtn.layer.masksToBounds = YES;
        _agreeBtn.layer.cornerRadius = 5;
        [_agreeBtn setTitle:NSLocalizedString(@"同意", nil) forState:UIControlStateNormal];
        [_agreeBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [_agreeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_agreeBtn setBackgroundColor:[CommUtls colorWithHexString:@"#F8B62D"]];
        [_agreeBtn addTarget:self action:@selector(dismissAlertView:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _agreeBtn;
}
- (UIButton *)diagreeBtn
{
    if (_diagreeBtn == nil) {
        _diagreeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _diagreeBtn.tag = 2;
        [_diagreeBtn setTitle:NSLocalizedString(@"不同意，退出应用",nil) forState:UIControlStateNormal];
        [_diagreeBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [_diagreeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_diagreeBtn addTarget:self action:@selector(dismissAlertView:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _diagreeBtn;
}



@end
